<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>上传文件到OSS</title>
</head>
<body>
<div class="container">
    <form>
        <div class="mb-3">
            <label for="file" class="form-label">选择文件</label>
            <input type="file" class="form-control" id="file" name="file" required>
        </div>
        <button type="submit" class="btn btn-primary">上传</button>
    </form>
</div>
<script type="text/javascript">
    const form = document.querySelector("form");
    form.addEventListener("submit", (event) => {
        event.preventDefault();
        const fileInput = document.querySelector("#file");
        const file = fileInput.files[0];
        console.log("submit");
        let fetch_url = "http://192.168.31.167:9090/g01_web/get_presigned_url_for_oss_upload";
        fetch(fetch_url, {method: "POST"}).then(async (response) => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.text();
        }).then((data) => {
            console.log(data)
            const dataVo = JSON.parse(data);
            const url = dataVo["url"];
            // console.log(url, dataVo["url"]);
            var xhr = new XMLHttpRequest();
            xhr.open("PUT", url, true);
            // 增加请求头，Content-Type为图片类型
            xhr.setRequestHeader("Content-Type", "image/png");
            xhr.setRequestHeader("Access-Control-Allow-Origin","*");
            xhr.onload = function (res_) {
                // 请求结束后，在此处编写处理代码。
                console.log("请求结束后，在此处编写处理代码\n", res_);
            };
            xhr.send(file);
        });
    });
</script>
</body>
</html>
